package com.example.project.controller.statistics;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.enums.ReportType;
import com.example.project.service.ProjectReportService;
import com.example.project.vo.ProjectReportRequest;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 报表导出Controller
 * 
 * @author ruoyi
 * @date 2025-10-24
 */
@Controller
@RequestMapping("/statistics/report")
public class ReportExportController extends BaseController {

    @Autowired
    private ProjectReportService projectReportService;
    
    private static final SimpleDateFormat FILE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss");

    /**
	 * 导出项目报表
	 */
	@RequiresPermissions("pm:statistics:export")
	@PostMapping("/export")
    @ResponseBody
	public void exportReport(HttpServletResponse response,
			@ModelAttribute ProjectReportRequest requestParam) {

		try {
			// 生成Excel报表
            Workbook workbook = projectReportService.generateExcelReport(requestParam);
            
            // 设置响应头
            String fileName = getFileName(requestParam.getReportType());
            
            // 对文件名进行URL编码，避免中文乱码
            String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8")
                    .replaceAll("\\+", "%20");
            
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            
            // 禁用缓存
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            
            // 写入响应流
            workbook.write(response.getOutputStream());
            response.getOutputStream().flush();
            
        } catch (Exception e) {
            logger.error("导出报表失败", e);
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"msg\":\"导出报表失败：" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                logger.error("写入错误响应失败", ex);
            }
        }
    }
    
    /**
     * 获取报表数据预览（用于前端展示）
     */
    @RequiresPermissions("pm:statistics:view")
    @GetMapping("/preview")
    @ResponseBody
    public AjaxResult previewReport(
            @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate,
            ReportType reportType) {
        
        try {
            ProjectReportRequest request = new ProjectReportRequest();
            request.setStartDate(startDate);
            request.setEndDate(endDate);
            request.setReportType(reportType);
            
            // 根据报表类型获取预览数据
            Object data = null;
            switch (reportType) {
                case PROJECT_BASIC_INFO:
                    data = projectReportService.getProjectBasicInfoData(request);
                    break;
                case PROJECT_STATISTICS:
                    data = projectReportService.getProjectStatisticsData(request);
                    break;
                case ISSUE_DETAIL_REPORT:
                    data = projectReportService.getIssueDetailData(request);
                    break;
                case CUSTOMER_PROJECT_REPORT:
                    data = projectReportService.getCustomerProjectData(request);
                    break;
                case COMPREHENSIVE_REPORT:
                    data = projectReportService.getComprehensiveAnalysisData(request);
                    break;
                default:
                    data = projectReportService.getProjectBasicInfoData(request);
            }
            
            return AjaxResult.success(data);
            
        } catch (Exception e) {
            logger.error("获取报表预览数据失败", e);
            return AjaxResult.error("获取报表预览数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 跳转到报表查看页面
     */
    @RequiresPermissions("pm:statistics:view")
    @GetMapping("/view")
    public String reportView() {
        return "pm/statistics/report_view";
    }
    
    /**
     * 获取报表类型枚举值
     */
    @RequiresPermissions("pm:statistics:view")
    @GetMapping("/reportTypes")
    @ResponseBody
    public AjaxResult getReportTypes() {
        try {
            ReportType[] reportTypes = ReportType.values();
            return AjaxResult.success(reportTypes);
        } catch (Exception e) {
            logger.error("获取报表类型失败", e);
            return AjaxResult.error("获取报表类型失败");
        }
    }
    
    /**
     * 生成文件名
     */
    private String getFileName(ReportType reportType) {
        String timestamp = FILE_DATE_FORMAT.format(new Date());
        String reportName = "";
        
        switch (reportType) {
            case PROJECT_BASIC_INFO:
                reportName = "项目基本信息报表";
                break;
            case PROJECT_STATISTICS:
                reportName = "项目统计报表";
                break;
            case ISSUE_DETAIL_REPORT:
                reportName = "问题明细报表";
                break;
            case CUSTOMER_PROJECT_REPORT:
                reportName = "客户项目关系报表";
                break;
            case COMPREHENSIVE_REPORT:
                reportName = "综合项目分析报表";
                break;
            default:
                reportName = "项目报表";
        }
        
        return reportName + "_" + timestamp + ".xlsx";
    }
}